package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.BabyHabitAdapter;
import com.jdy.haoduoai.adapter.HabitPlanAdapter;
import com.jdy.haoduoai.adapter.HabitPlanAdapter.OnSetAlarmListener;
import com.jdy.haoduoai.adapter.MyTaskAdapter;
import com.jdy.haoduoai.adapter.MyTaskAdapter.OnCheckListener;
import com.jdy.haoduoai.adapter.OnPreviewClickListener;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.fragment.TabIndexFragment;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.HabitMedia;
import com.jdy.haoduoai.model.HabitPlan;
import com.jdy.haoduoai.model.LeAudioActionItem;
import com.jdy.haoduoai.model.LeAudioActionPlan;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeResourceItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.LeWatchingPlan;
import com.jdy.haoduoai.model.MainPageResult;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.socket.DeviceStateListener;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageLoader;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.ScrollViewWithListView;
import com.jdy.haoduoai.view.calendar.adpter.WeekCalendarAdpter.OnDateSelectListener;
import com.jdy.haoduoai.view.calendar.fragment.MyCalendarFragment;
import com.jdy.haoduoai.view.swipemenu.SwipeMenu;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuCreator;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuItem;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuListView;
import com.jdy.haoduoai.view.visualizer.FrequencyDistributionBarView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

import static android.view.View.GONE;

//import com.jdy.haoduoai.R;

/**
 * 
 * 
 * @author hf
 * 
 */
public class BabyCalenderActivity extends BaseActivity implements
    OnClickListener, OnScrollListener, OnCheckListener,
        OnDataReceivedListener, OnSetAlarmListener, OnDateSelectListener, BabyHabitAdapter.OnConfirmClassListener , BabyHabitAdapter.OnSetAlarmListener2, DeviceStateListener {

  @InjectView(id = R.id.imgbtn_back, click = true)
  private View imgbtn_back;
  @InjectView(id = R.id.rela_btnPreMonth, click = true)
  private RelativeLayout rela_btnPreMonth;
  @InjectView(id = R.id.rela_btnNextMonth, click = true)
  private RelativeLayout rela_btnNextMonth;
  @InjectView(id = R.id.tvCurrentMonth, click = true)
  private TextView tvCurrentMonth;
  @InjectView(id = R.id.device_stateview, click = true)
  private FrequencyDistributionBarView device_stateview;
  @InjectView(id = R.id.custom_channel)
  private LinearLayout custom_channel;
  @InjectView(id = R.id.h_scrollview)
  private HorizontalScrollView h_scrollview;
  @InjectView(id = R.id.task_views, click = true)
  private ScrollViewWithListView task_views;
  @InjectView(id = R.id.tv_task)
  private TextView tv_task;
  @InjectView(id = R.id.img_defaultempty)
  private ImageView img_defaultempty; // 过期或未来占位图
  @InjectView(id = R.id.view_habit)
  private View view_habit;
  @InjectView(id = R.id.llayout_defaultempty)
  private LinearLayout llayout_defaultempty; // 过期或未来占位图
  @InjectView(id = R.id.list_habitplan, click = true)
  private SwipeMenuListView listview_habitplan;
  @InjectView(id = R.id.btn_beginclass, click = true)
  private Button btn_beginclass;
  @InjectView(id = R.id.layout_task, click = true)
  private LinearLayout layout_task;
  @InjectView(id = R.id.tv_growthtitle)
  private TextView tv_growthtitle;
  @InjectView(id = R.id.view_content)
  private LinearLayout view_content;
  @InjectView(id = R.id.rel_top)
  private View rel_top;
  @InjectView(id = R.id.rel_teacher)
  private View rel_teacher;

  @InjectView(id = R.id.teacherclass_views, click = true)
  private ScrollViewWithListView teacherclass_views;
  private BabyHabitAdapter mTeacherClassApater;
  private ArrayList<HabitPlan> arrayListTeacherClass;

  private TextView tv_habitlabel;
  private TextView tv_recustom;
  private HabitPlanAdapter mHabitPlanAdapter;
  private ArrayList<HabitPlan> arrayListHabitPlan;
  private MyTaskAdapter mMyTaskAdapter;
  private ArrayList<LeAudioActionItem> listLeActionItem = new ArrayList<LeAudioActionItem>();
  private ImageLoader mImageLoader;
  private boolean isPageChanged;
  private boolean isLoading;
  private HabitMedia mHabitMusic;
  private boolean isPlayingMusic;

  private PlayState mPlayState = PlayState.None;
  private int mVideoId = -1;

  private MyCalendarFragment myCalenderFragment;
  private LeUser mLeUser;
  private String mCustomDate;

  private LeWatchingPlan mLeWatchingPlanWeek;
  private MainPageResult mMainPageResult;
  private String mCurDay;
  private String selectQueryDate;
  // -1：过去 0：当天 1：将来
  private int dateStatus = -2;
  private TextView mLastTv = null;
  private int mSelectedId = -1;
  private String mLastUrl;
  private boolean mIsPreviewing = false;

  private void bindService() {
    SocketThreadManager.getInstance().setDeviceStateListener(this);
 //   SocketThreadManager.getInstance().requestDeviceDetails();
  }

  private void startAnimation(TextView tv) {
    if (tv != null) {
      AnimationDrawable ad = (AnimationDrawable) ContextCompat.getDrawable(this,R.drawable.preview_anim);
      tv.setCompoundDrawablesWithIntrinsicBounds(null, null, ad, null);
      ad.start();
    }
  }

  private void stopAnimation(TextView tv) {
    if (tv != null) {

      Drawable[] drawables = tv.getCompoundDrawables();

      Drawable rightD = drawables[2];

      if (rightD instanceof AnimationDrawable) {
        AnimationDrawable ad = (AnimationDrawable) rightD;

        if (ad != null && ad.isRunning()) {
          ad.stop();
        }

        Drawable d = ContextCompat.getDrawable(this,R.drawable.preview_record_img);

        tv.setCompoundDrawablesWithIntrinsicBounds(null, null, d, null);

      } else {
        return;
      }
    }
  }

  private void getMachineStatus() {

    try {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("code", 202);
      jsonObject.put("act", "videostatu");
      SocketThreadManager.getInstance().send(jsonObject.toString());
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

//    new CustomAsyncTask(this, new IAsyncTask() {
//      @Override
//      public void onRecieveData(Activity activity, ResponseResult result) {
//        if (result.isSuccess()) {
//       //   parseJson(result.data);
//        }
//      }
//
//      @Override
//      public ResponseResult doInbackground(Activity activity) {
//        if (mLeUser == null) {
//          mLeUser = Tools.restoreLeUser();
//        }
//
//        String sno = mLeUser.sno;
//        String macId = mLeUser.machine.id;
//
//        HashMap<String, Object> param_ = new HashMap<String, Object>();
//        param_.put(HttpUtils.TAG_SNO_I, sno);
//        param_.put("act", "videostatu");
//        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
//
//        return HttpUtils.startRequest(HttpUtils.API_URL
//                        + "/api/1.0/device/remote", param_,
//                HttpUtils.TAG_GET_REQUEST);
//      }
//    }).execute();
  }

  @Override
  protected void onPause() {
    super.onPause();

    MobclickAgent.onPause(this);
  }



  @Override
  protected void onResume() {
    super.onResume();

    MobclickAgent.onResume(this);

    if (!LeConfig.isDeviceConnect) {
      if (device_stateview != null) {
        device_stateview.setPlaying(false);
      }
    }

    if (!LeConfig.isInternetAvailable) {
      if (device_stateview != null) {
        device_stateview.setPlaying(false);
      }
    }

//    try {
//      JSONObject jsonObject = new JSONObject();
//      jsonObject.put("code", 202);
//      jsonObject.put("act", "videostatu");
//      SocketThreadManager.getInstance().send(jsonObject.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    } catch (Exception e) {
//      e.printStackTrace();
//    }

  //  SocketThreadManager.getInstance().requestDeviceDetails();

  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentViewWithoutInject(R.layout.activity_dummy);

    showloading("");

    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        setContentView(R.layout.baby_plan);
        hideTitleView();

        bindService();
        dateStatus = 0;

        SocketThreadManager.getInstance().setDataReceivedListener(BabyCalenderActivity.this);

        updateBeginClassBtn();
        initView();
        initData();
        loadDataByMonth(mCurDay);
        loadHabitsPlan(mCurDay);
        selectQueryDate = mCurDay;

        if (myCalenderFragment != null) {
          String year = myCalenderFragment.getMonthViewDateStr()
              .substring(0, 4);
          String month = myCalenderFragment.getMonthViewDateStr().substring(5,
              7);
          tvCurrentMonth.setText(year + "年 " + month + "月");
        }
      }
    }, 50);


    SocketThreadManager.getInstance().setDataReceivedListener(BabyCalenderActivity.this);

    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
      //  if (mImHelper != null && mImHelper.isLogin()) {

        getMachineStatus();

//
//          try {
//            JSONObject dataJson = new JSONObject();
//            dataJson.put("code", 202);
//            dataJson.put("act", "machineinfo");
//            SocketThreadManager.getInstance().send(dataJson.toString());
//          } catch (JSONException e) {
//            e.printStackTrace();
//          } catch (Exception e) {
//            e.printStackTrace();
//          }
       // }
      }
    }, 1000);

//    getMachineStatus();

//    TIMManager.getInstance().setConnectionListener(new TIMConnListener() {
//
//      @Override
//      public void onWifiNeedAuth(String arg0) {
//        // TODO Auto-generated method stub
//
//      }
//
//      @Override
//      public void onDisconnected(int arg0, String arg1) {
//        LeConfig.isDeviceConnect = false;
//
//        if (device_stateview != null) {
//          device_stateview.setPlaying(false);
//        }
//      }
//
//      @Override
//      public void onConnected() {
//        // TODO Auto-generated method stub
//
//      }
//    });

  }

  private void updateBeginClassBtn() {
    switch (dateStatus) {
    case -1:
      btn_beginclass.setEnabled(true);
      // TODO
      break;
    case 0:
      btn_beginclass.setEnabled(true);
      btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
      break;
    case 1:
      btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
      btn_beginclass.setEnabled(false);
      break;

    default:
      break;
    }
  }

  @SuppressLint("ClickableViewAccessibility")
  private void initView() {
    task_views = (ScrollViewWithListView) findViewById(R.id.task_views);
    tv_habitlabel = (TextView) findViewById(R.id.tv_habitlabel);

    teacherclass_views = (ScrollViewWithListView)
            findViewById(R.id.teacherclass_views);
    teacherclass_views.setEnabled(false);

    if (btn_beginclass != null) {
      btn_beginclass.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    }

    tv_recustom = (TextView) findViewById(R.id.tv_recustom);
    tv_recustom.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    tv_recustom.setOnClickListener(this);

    listview_habitplan = (SwipeMenuListView) findViewById(R.id.list_habitplan);
    listview_habitplan.setHiderMore(true);

    SwipeMenuCreator creator = new SwipeMenuCreator() {

      @Override
      public void create(SwipeMenu menu, int pos) {
        if (arrayListHabitPlan.get(pos) != null && arrayListHabitPlan.get(pos).is_customized == 2) {
          return;
        }

        SwipeMenuItem deleteItem = new SwipeMenuItem(BabyCalenderActivity.this);
        deleteItem
            .setBackground(new ColorDrawable(Color.rgb(0xF0, 0xF0, 0xF0)));
        deleteItem.setWidth(Tools.getPixelByDip(BabyCalenderActivity.this, 90));
        deleteItem.setIcon(R.drawable.btn_del);
        menu.addMenuItem(deleteItem);
      }
    };

    listview_habitplan.setMenuCreator(creator);
    listview_habitplan
        .setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
          @Override
          public boolean onMenuItemClick(final int position, SwipeMenu menu,
              int index) {
            switch (index) {
            case 0:

              new CustomAsyncTask(BabyCalenderActivity.this, new IAsyncTask() {
                @Override
                public void onRecieveData(Activity activity,
                    ResponseResult result) {
                  if (result.isSuccess()) {
                    if (arrayListHabitPlan != null
                        && position < arrayListHabitPlan.size()) {
                      arrayListHabitPlan.remove(position);
                      mHabitPlanAdapter.notifyDataSetChanged();
                    }
                  } else {
                    if (Tools.isNotNullStr(result.data)) {
                      Toast.makeText(BabyCalenderActivity.this, result.data,
                          Toast.LENGTH_SHORT).show();
                    }
                  }

                }

                @Override
                public ResponseResult doInbackground(Activity activity) {
                  HashMap<String, Object> param_ = new HashMap<String, Object>();
                  LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                  if (lu == null) {
                    lu = Tools.restoreLeUser();
                  }

                  param_.put(HttpUtils.TAG_SNO_I, lu.sno);


                  if (arrayListHabitPlan.get(position).is_customized == 1) {
                    return HttpUtils.startRequest(HttpUtils.API_URL
                                    + "/api/2.0/operation/habit/habits_customized_plan/"
                                    + arrayListHabitPlan.get(position).id, param_,
                            HttpUtils.TAG_DELETE_REQUEST);
                  } else {
                    return HttpUtils.startRequest(HttpUtils.API_URL
                                    + "/api/2.0/operation/habit/habits_plan/"
                                    + arrayListHabitPlan.get(position).id, param_,
                            HttpUtils.TAG_DELETE_REQUEST);
                  }


                }
              }).execute();

              break;
            }
            return false;
          }
        });

    // set SwipeListener
    listview_habitplan
        .setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

          @Override
          public void onSwipeStart(int position) {
            // swipe start
          }

          @Override
          public void onSwipeEnd(int position) {
            // swipe end

          }

          @Override
          public void onClickSwipeOpen(int position) {

          }
        });

  }

  private void updateWeekRecomAnim(String dateStr) {
    mLeWatchingPlanWeek = null;

    if (Tools.isNotEmpty(mMainPageResult)
        && Tools.isNotEmpty(mMainPageResult.clause)
        && !mMainPageResult.clause.isEmpty()) {
      for (LeWatchingPlan item : mMainPageResult.clause) {
        if (dateStr.contains(item.date)) {
          mLeWatchingPlanWeek = item;
          break;
        }
      }
    }

    fillRecomAnimLineLayout();
  }

  @SuppressLint("SimpleDateFormat")
  private void updateDayTask(String dataStr) {
    if (listLeActionItem == null) {
      listLeActionItem = new ArrayList<>();
    } else {
      listLeActionItem.clear();
    }

    int plan_id = 0;
    if (Tools.isNotEmpty(mMainPageResult)) {
      if (mMainPageResult.audio_interaction != null
          && !mMainPageResult.audio_interaction.isEmpty()) {
        for (LeAudioActionPlan item : mMainPageResult.audio_interaction) {
          if (item != null && item.date.contains(dataStr)) {
            listLeActionItem.addAll(item.actions);
            plan_id = item.interaction_id;
            break;
          }
        }
      }
    }

    if (listLeActionItem == null) {
      listLeActionItem = new ArrayList<>();
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String strToday = sdf.format(Calendar.getInstance().getTime());

    boolean clickable;
    if (dataStr.compareTo(strToday) > 0) {
      clickable = false;
    } else if (dataStr.compareTo(strToday) < 0) {
      if (LeXiaoXiaoBanApp.getInstance().getGrowth_period() == mMainPageResult.growth_info.growth_period) {
        clickable = true;
      } else {
        clickable = false;
      }
    } else {
      clickable = true;
    }

    mMyTaskAdapter = new MyTaskAdapter(this, listLeActionItem, plan_id,
        clickable);


    mMyTaskAdapter.setOnPreviewClickListener(new OnPreviewClickListener() {
      @Override
      public void onPreviewClick(TextView tv,int id, String mp3_url) {
        if (id != mSelectedId) {
          stopAnimation(mLastTv);
          startAnimation(tv);
          mIsPreviewing = true;
          previewMp3(mp3_url);
        } else {
          mIsPreviewing = !mIsPreviewing;
          if(mIsPreviewing) {
            startAnimation(tv);
            previewMp3(mp3_url);
          } else {
            stopAnimation(tv);
            releaseMp3Player();
          }
        }
        mLastTv = tv;
        mSelectedId = id;
      }
    });


    mMyTaskAdapter.setOnCheckListener(this);
    task_views.setAdapter(mMyTaskAdapter);
    Tools.setListViewHeightBasedOnChildren(task_views);
    mMyTaskAdapter.notifyDataSetChanged();
  }


  private void previewMp3(String mp3_url) {
    releaseMp3Player();

    boolean excepthappen = false;
    if (mp3Player == null)
      mp3Player = new MediaPlayer();
    try {
      mp3Player.setDataSource(mp3_url);
    } catch (IllegalArgumentException e) {
      excepthappen = true;
      e.printStackTrace();
    } catch (SecurityException e) {
      excepthappen = true;
      e.printStackTrace();
    } catch (IllegalStateException e) {
      excepthappen = true;
      e.printStackTrace();
    } catch (IOException e) {
      excepthappen = true;
      e.printStackTrace();
    }

    if ( !excepthappen ) {
      try {
        mp3Player.prepare();
        mp3Player.start();
        mp3Player.setOnCompletionListener(mediaPlayerListener);
      } catch (IllegalArgumentException e) {
        excepthappen = true;
        e.printStackTrace();
      } catch (SecurityException e) {
        excepthappen = true;
        e.printStackTrace();
      } catch (IllegalStateException e) {
        excepthappen = true;
        e.printStackTrace();
      } catch (IOException e) {
        excepthappen = true;
        e.printStackTrace();
      }
    } else {
      // toastShow("暂时无法试听");
    }
  }

  private MediaPlayer.OnCompletionListener mediaPlayerListener = new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
      //stopAnimation();
      if (mLastTv!=null) {
        stopAnimation(mLastTv);
      }
    }
  };


  private MediaPlayer mp3Player;

  private void releaseMp3Player() {
    if (mp3Player != null) {
      mp3Player.stop();
      mp3Player.setOnCompletionListener(null);
      mp3Player.release();
      mp3Player = null;
    }
  }

  @SuppressLint({ "HandlerLeak", "SimpleDateFormat" })
  private void initData() {
    myCalenderFragment = new MyCalendarFragment(new Handler() {
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
      }
    }, true);

    myCalenderFragment.setOnDateSelectListener(this);
    getSupportFragmentManager().beginTransaction()
        .add(R.id.re_cotent, myCalenderFragment).show(myCalenderFragment)
        .commit();

    handler.postDelayed(new Runnable() {

      @Override
      public void run() {
        myCalenderFragment.switch2MonthView();

        String year = myCalenderFragment.getMonthViewDateStr().substring(0, 4);
        String month = myCalenderFragment.getMonthViewDateStr().substring(5, 7);
        tvCurrentMonth.setText(year + "年 " + month + "月");
      }
    }, 1500);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    mCurDay = sdf.format(Calendar.getInstance().getTime());

    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }

    if (mLeUser == null) {
      Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
      Intent intent = new Intent(this, LoginActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
          | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
    }
  }

  private void addEmptyView() {
    if (listview_habitplan.getEmptyView() != null) {
      return;
    }

    View emptyView = LayoutInflater.from(this).inflate(
            R.layout.tabindex_emptyview, null);

    LinearLayout root_view = (LinearLayout) emptyView
            .findViewById(R.id.root_view);
    Button btn_customhabit = (Button) emptyView
            .findViewById(R.id.btn_customhabit);
    btn_customhabit.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    btn_customhabit.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(BabyCalenderActivity.this, MyPainPointSelectActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);

      }
    });

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    root_view.setOrientation(LinearLayout.VERTICAL);
    root_view.setGravity(Gravity.CENTER);
    emptyView.setLayoutParams(params);

    ((ViewGroup) listview_habitplan.getParent()).addView(emptyView);
    listview_habitplan.setEmptyView(emptyView);
  }

  @SuppressLint("SimpleDateFormat")
  private void loadHabitsPlan(final String dayStr) {

    if (Tools.isNotEmpty(dayStr)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String strToday = sdf.format(Calendar.getInstance().getTime());

      TabIndexFragment.allowEditTime = dayStr.compareTo(strToday);
    }

    if (isLoading || Tools.isEmpty(dayStr)) {
      return;
    }

    isLoading = true;

    Async.start(new Func0<ResponseResult>() {
      @Override
      public ResponseResult call() {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put("date", dayStr);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/habit/habits_plan", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).filter(new Func1<ResponseResult, Boolean>() {
      @Override
      public Boolean call(ResponseResult arg0) {
        return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
      }
    }).doOnCompleted(new Action0() {
      @Override
      public void call() {

        if (arrayListHabitPlan == null) {
          arrayListHabitPlan = new ArrayList<HabitPlan>();
        }

        if (arrayListTeacherClass == null) {
          arrayListTeacherClass = new ArrayList<HabitPlan>();
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {

              if (mHabitPlanAdapter == null) {
                  mHabitPlanAdapter = new HabitPlanAdapter(BabyCalenderActivity.this,
                          arrayListHabitPlan, listview_habitplan);
              } else {
                  mHabitPlanAdapter.updateListData(arrayListHabitPlan);
              }

            mHabitPlanAdapter.setOnSetAlarmListener(BabyCalenderActivity.this);
            listview_habitplan.setAdapter(mHabitPlanAdapter);


            if (mTeacherClassApater == null) {
              if (arrayListTeacherClass != null && !arrayListTeacherClass.isEmpty()) {
                mTeacherClassApater = new BabyHabitAdapter(BabyCalenderActivity.this, arrayListTeacherClass);
                mTeacherClassApater.setConfirmClassListener(BabyCalenderActivity.this);
                mTeacherClassApater.setOnSetAlarmListener(BabyCalenderActivity.this);
              } else {
                mTeacherClassApater = new BabyHabitAdapter(BabyCalenderActivity.this,
                        new ArrayList<HabitPlan>());
                mTeacherClassApater.setConfirmClassListener(BabyCalenderActivity.this);
                mTeacherClassApater.setOnSetAlarmListener(BabyCalenderActivity.this);
              }

              teacherclass_views.setAdapter(mTeacherClassApater);
            } else {
              mTeacherClassApater.setData(arrayListTeacherClass);
              mTeacherClassApater.notifyDataSetChanged();
            }

            if (arrayListTeacherClass == null || arrayListTeacherClass.isEmpty()) {
              rel_teacher.setVisibility(View.GONE);
            } else {
              rel_teacher.setVisibility(View.VISIBLE);
            }

            addEmptyView();

            SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
            String strCurentDate = formatter.format(Calendar.getInstance()
                .getTime());
            String date[] = strCurentDate.split(" ");

            if (arrayListHabitPlan != null) {
              for (int i = 0; i < arrayListHabitPlan.size(); i++) {
                HabitPlan item = arrayListHabitPlan.get(i);

                if (item != null) {
                  if (item.time.compareTo(date[1]) >= 0) {
                    if (item.time.compareTo(date[1]) == 0) {
                      item.allowEditTime = false;
                    }
                    if (!isPlayingMusic) {
                      listview_habitplan.setSelection(i);
                    }
                    break;
                  } else {
                    item.allowEditTime = false;
                  }
                }
              }
            }

            if (arrayListHabitPlan == null || arrayListHabitPlan.isEmpty()) {
              // tv_recustom.setVisibility(View.GONE);
//              view_habit.setVisibility(GONE);
//              tv_habitlabel.setVisibility(GONE);
//              listview_habitplan.setVisibility(GONE);
            } else {
              // tv_recustom.setVisibility(View.VISIBLE);
              view_habit.setVisibility(View.VISIBLE);
              tv_habitlabel.setVisibility(View.VISIBLE);
              listview_habitplan.setVisibility(View.VISIBLE);
            }

            Tools.setListViewHeightBasedOnChildren(listview_habitplan);
            mHabitPlanAdapter.notifyDataSetChanged();

            if (rel_top != null) {
              rel_top.setFocusable(true);
              rel_top.setFocusableInTouchMode(true);
              rel_top.requestFocus();
            }
          }
        });

        isLoading = false;
      }
    }).subscribe(new Action1<ResponseResult>() {
      @SuppressWarnings("unchecked")
      @Override
      public void call(ResponseResult result) {

        if (arrayListTeacherClass == null) {
          arrayListTeacherClass = new ArrayList<HabitPlan>();
        }

        if (Tools.isNotEmpty(result) && Tools.isNotEmpty(result.data)) {
          arrayListHabitPlan = (ArrayList<HabitPlan>) JsonSerializer
              .getInstance().deserialize(result.data, ArrayList.class,
                  HabitPlan.class);

          for (HabitPlan item : arrayListHabitPlan) {
            if (item.is_customized == 2) {
              arrayListTeacherClass.add(item);
            }
          }

          if (arrayListHabitPlan != null) {
            arrayListHabitPlan.removeAll(arrayListTeacherClass);
          }

        } else {
          arrayListHabitPlan = new ArrayList<HabitPlan>();
          arrayListTeacherClass = new ArrayList<HabitPlan>();
        }
      }
    });
  }

  @SuppressLint("SimpleDateFormat")
  private void checkAnimAndTaskNumber(String dateStr) {
    if (Tools.isNotEmpty(dateStr)) {

      String[] createTime = mLeUser.machine.created_at.split(" ");

      if (dateStr.compareTo(mLeUser.machine.dob) >= 0
          && dateStr.compareTo(createTime[0]) < 0
          || dateStr.compareTo(mLeUser.machine.dob) < 0) {
        tv_task.setVisibility(GONE);
        layout_task.setVisibility(GONE);
       // view_content.setVisibility(GONE);
       // tv_growthtitle.setVisibility(GONE);

        llayout_defaultempty.setVisibility(View.VISIBLE);
        img_defaultempty.setImageResource(R.drawable.date_passed);
      } else {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strToday = sdf.format(Calendar.getInstance().getTime());

        if (dateStr.compareTo(strToday) > 0
            && (mMainPageResult.audio_interaction == null || mMainPageResult.audio_interaction
                .isEmpty())) {
          tv_task.setVisibility(GONE);
          layout_task.setVisibility(GONE);
        //  view_content.setVisibility(GONE);
         // tv_growthtitle.setVisibility(GONE);

          llayout_defaultempty.setVisibility(View.VISIBLE);
          img_defaultempty.setImageResource(R.drawable.date_future);
        } else {
          tv_task.setVisibility(View.VISIBLE);
          layout_task.setVisibility(View.VISIBLE);
        //  view_content.setVisibility(View.VISIBLE);
        //  tv_growthtitle.setVisibility(View.VISIBLE);
          llayout_defaultempty.setVisibility(GONE);
        }
      }

    } else {
      tv_task.setVisibility(View.VISIBLE);
      layout_task.setVisibility(View.VISIBLE);
     // view_content.setVisibility(View.VISIBLE);
     // tv_growthtitle.setVisibility(View.VISIBLE);
      llayout_defaultempty.setVisibility(GONE);
    }
  }

  private void loadDataByMonth(final String strDate) {
    // showloading("");

    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressLint("SimpleDateFormat")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (Tools.isNotNullStr(result.data)) {
            mMainPageResult = JsonSerializer.getInstance().deserialize(
                result.data, MainPageResult.class);

            if (Tools.isNotEmpty(mMainPageResult)) {

              updateWeekRecomAnim(strDate);
              updateDayTask(strDate);

            }
          }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strToday = sdf.format(Calendar.getInstance().getTime());

        if (strDate.compareTo(strToday) < 0) {
          dateStatus = -1;
        } else if (strDate.compareTo(strToday) == 0) {
          dateStatus = 0;
        } else if (strDate.compareTo(strToday) > 0) {
          dateStatus = 1;
        }
        updateBeginClassBtn();

        checkAnimAndTaskNumber(strDate);

        isPageChanged = false;
        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put("date", strDate);

        return HttpUtils.startRequest(
            HttpUtils.API_URL + "/api/2.0/index/date", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private ArrayList<ImageView> imgList = new ArrayList<ImageView>();

  private void fillRecomAnimLineLayout() {
    h_scrollview.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View arg0, MotionEvent arg1) {

        Log.e("chen", "HorizontalScrollView-onTouch");

        // 不能滑动
        return true;
        // 可以滑动
        // return false;
      }
    });

    custom_channel.removeAllViews();

    // View line = new View(this);
    int pCount = 0;
    if (Tools.isNotEmpty(mLeWatchingPlanWeek)
        && Tools.isNotEmpty(mLeWatchingPlanWeek.resources)
        && !mLeWatchingPlanWeek.resources.isEmpty()) {
      pCount = mLeWatchingPlanWeek.resources.size();
    }

    if (pCount > 3) {
      pCount = 3;
    }

    DisplayMetrics dm;
    int screenW, screenH;

    dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm); // 得到 屏幕的宽度
    screenW = dm.widthPixels;
    screenH = dm.heightPixels;

    imgList.clear();
    for (int i = 0; i < pCount; i++) {
      View v = LayoutInflater.from(this).inflate(R.layout.class_list_item2,
          custom_channel, false);

      final LeResourceItem item = mLeWatchingPlanWeek.resources.get(i);

      LayoutParams para3333;
      para3333 = v.getLayoutParams();

      para3333.width = (screenW - Tools.getPixelByDip(this, 56)) / 3;
      v.setLayoutParams(para3333);

      custom_channel.addView(v);
      final ImageView channelIcon = (ImageView) v.findViewById(R.id.headicon);

      final TextView title = (TextView) v.findViewById(R.id.editor);
      final TextView playtimes = (TextView) v.findViewById(R.id.playtimes);
      final TextView tv_name2 = (TextView) v.findViewById(R.id.tv_name2);
      final TextView tv_label1 = (TextView) v.findViewById(R.id.tv_label1);
      final TextView tv_label2 = (TextView) v.findViewById(R.id.tv_label2);
      final ImageView img_playanim = (ImageView) v
          .findViewById(R.id.img_playanim);
      img_playanim.setTag(item.resource_id);
      imgList.add(img_playanim);

      if (item.tags == null || item.tags.isEmpty()) {
        tv_label1.setVisibility(View.INVISIBLE);
        tv_label2.setVisibility(View.INVISIBLE);
      } else if (item.tags.size() == 1) {
        tv_label1.setText(item.tags.get(0));
        tv_label2.setVisibility(View.INVISIBLE);
      } else if (item.tags.size() > 1) {
        tv_label1.setText(item.tags.get(0));
        tv_label2.setText(item.tags.get(1));
      }

      tv_name2.setText(item.resource_name);
      title.setText(item.album_name);
      playtimes.setText(DateUtils.getTime2(item.length));

      if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this);
      }

      if (Tools.isNotEmpty(item) && Tools.isNotEmpty(item.album_cover)) {
        Picasso.with(this).load(item.album_cover)
            .placeholder(R.drawable.default_img_listitem)
            .error(R.drawable.default_img_listitem)
            .into(channelIcon, new Callback() {
              @Override
              public void onError() {
                mImageLoader.DisplayImage(item.album_cover, channelIcon, false);
              }

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub
              }
            });
      } else   if (Tools.isNotEmpty(item) && Tools.isNotEmpty(item.album_cover2)) {
        Picasso.with(this).load(item.album_cover2)
                .placeholder(R.drawable.default_img_listitem)
                .error(R.drawable.default_img_listitem)
                .into(channelIcon, new Callback() {
                  @Override
                  public void onError() {
                    mImageLoader.DisplayImage(item.album_cover2, channelIcon, false);
                  }

                  @Override
                  public void onSuccess() {
                    // TODO Auto-generated method stub
                  }
                });
      }

      final int videoNum = i;

      img_playanim.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
      img_playanim.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          if (mMainPageResult != null && mMainPageResult.clause != null
              && !mMainPageResult.clause.isEmpty()) {
            if (mPlayState == PlayState.None || mPlayState == PlayState.Offline
                || mPlayState == PlayState.Stop
                || mPlayState == PlayState.NoResource) {
              playvideo(mMainPageResult.clause.get(0).clause_id, "radio",
                  videoNum, img_playanim);
              img_playanim.setBackgroundResource(R.drawable.anim_pause);

              for (int i = 0; i < imgList.size(); i++) {
                if (i != videoNum) {
                  imgList.get(i).setBackgroundResource(R.drawable.anim_play);
                }
              }
            } else {
              if (mVideoId != -1 && mVideoId == item.resource_id) {
                if (mPlayState == PlayState.Playing) {
                //  if (mImHelper != null && mImHelper.isLogin()) {
                    try {
                      JSONObject jsonObject = new JSONObject();
                      jsonObject.put("code", 202);
                      jsonObject.put("act", "ctlvideo");
                      jsonObject.put("data", "pause");
                      SocketThreadManager.getInstance().send(jsonObject.toString());
                    } catch (JSONException e) {
                      e.printStackTrace();
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
               //   }
                  img_playanim.setBackgroundResource(R.drawable.anim_play);
                } else {
                //  if (mImHelper != null && mImHelper.isLogin()) {
                    try {
                      JSONObject jsonObject = new JSONObject();
                      jsonObject.put("code", 202);
                      jsonObject.put("act", "ctlvideo");
                      jsonObject.put("data", "resume");
                      SocketThreadManager.getInstance().send(jsonObject.toString());
                    } catch (JSONException e) {
                      e.printStackTrace();
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                //  }
                  img_playanim.setBackgroundResource(R.drawable.anim_pause);
                }
              } else {
                playvideo(mMainPageResult.clause.get(0).clause_id, "radio",
                    videoNum, img_playanim);
                img_playanim.setBackgroundResource(R.drawable.anim_pause);

                for (int i = 0; i < imgList.size(); i++) {
                  if (i != videoNum) {
                    imgList.get(i).setBackgroundResource(R.drawable.anim_play);
                  }
                }
              }
            }
          }
        }
      });

      // if (i != pCount - 1) {
      // line = new View(this);
      // line.setBackgroundColor(0xffeeeeee);
      // custom_channel.addView(line, new LinearLayout.LayoutParams(
      // LayoutParams.MATCH_PARENT, 2));
      // }
    }
  }

  private void playvideo(final int sid, final String status,
      final int clause_num, final ImageView img) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          toastShow("已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            toastShow("已推送到设备播放");
//          } else {
//            toastShow("未连接到设备，请检查设备联网情况！");
//            img.setBackgroundResource(R.drawable.anim_play);
//          }
        } else {
          if (Tools.isNotNullStr(result.data)) {
            toastShow(result.data);
          }

          img.setBackgroundResource(R.drawable.anim_play);
        }

        switch (dateStatus) {
        // case -1:
        // // btn_beginclass.setBackgroundResource(R.drawable.makeupcalss_nor);
        // break;
        case 0:
          btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
          break;
        case 1:
          btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
          break;

        default:
          break;
        }
      }

      @SuppressWarnings("unused")
      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        int uid = -1, volume = -1, minutes = -1;
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "clause");
       // param_.put("mode", "im");
        param_.put("clause_num", String.valueOf(clause_num + 1));
        // param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.tv_recustom:
      Intent intent = new Intent();
      //intent.setClass(this, PainPointSelectActivity.class);
      intent.setClass(this, MyPainPointSelectActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      startActivity(intent);
      break;
    case R.id.btn_beginclass:

      switch (dateStatus) {
      case -1:
        // btn_beginclass.setBackgroundResource(R.drawable.makeupcalss_pressed);
        break;
      case 0:
        // btn_beginclass.setBackgroundResource(R.drawable.begin_class_pressed);
        break;
      case 1:
        btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
        break;
      default:
        break;
      }

      break;
    case R.id.device_stateview:
      if (LeConfig.isLogin) {
        startActivity(new Intent(this, DevicePropertyActivity.class));
      } else {
        Intent intent0 = new Intent(this, LoginActivity.class);
        intent0.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent0);
      }
      break;
    case R.id.imgbtn_back:
      finish();
      break;
    case R.id.rela_btnPreMonth:
      if (myCalenderFragment != null) {
        myCalenderFragment.pagerLast();
      }
      break;
    case R.id.rela_btnNextMonth:
      if (myCalenderFragment != null) {
        myCalenderFragment.pagerNext();
      }
      break;
    default:
      break;
    }
  }

  @SuppressLint("SimpleDateFormat")
  @Override
  public void changeDate(String date, String viewType) {

    if (Tools.isEmpty(date)) {
      return;
    }

    String year = date.substring(0, 4);
    String month = date.substring(5, 7);

    String firstDayThisMonth = null, endDayThisMonth = null;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Date dateee;
    try {
      dateee = sdf.parse(date);
      Calendar cal = Calendar.getInstance();
      cal.setTime(dateee);
      cal.set(Calendar.DAY_OF_MONTH, 1);
      cal.getTime();
      firstDayThisMonth = sdf.format(cal.getTime()) + "";

      cal = Calendar.getInstance();
      cal.setTime(dateee);
      cal.set(Calendar.DAY_OF_MONTH,
          cal.getActualMaximum(Calendar.DAY_OF_MONTH));
      cal.getTime();
      endDayThisMonth = sdf.format(cal.getTime()) + "";
    } catch (ParseException e) {
      e.printStackTrace();
    }

    tvCurrentMonth.setText(year + "年 " + month + "月");

    isPageChanged = true;
    mCustomDate = date;

    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu == null) {
      lu = Tools.restoreLeUser();
    }

    if (Tools.isNotEmpty(lu) && mCustomDate != null) {
      LeMachine lm = lu.machine;
      String dateNow = mCustomDate.substring(0, mCustomDate.length() - 3);

      if (lm != null && lm.dob.contains(dateNow)) {
        if (myCalenderFragment != null) {
          myCalenderFragment.setMonthViewScrollble(false);
        }
      } else {
        if (myCalenderFragment != null) {
          myCalenderFragment.setMonthViewScrollble(true);
        }
      }
    } else {
      if (myCalenderFragment != null) {
        myCalenderFragment.setMonthViewScrollble(true);
      }
    }

    tvCurrentMonth.setText(year + "年 " + month + "月");

    if (isPageChanged) {
      String dateString = date;

      if (!dateString.contains(mCurDay)) {
        dateString = dateString.substring(0, 7) + "-01";
      }

      String queryDateStr = mCustomDate;

      if (viewType.contains("week")) {
        loadDataByMonth(mCustomDate);
        loadHabitsPlan(mCustomDate);
        selectQueryDate = mCustomDate;
      } else {
        if (myCalenderFragment.getSelectTime().compareTo(endDayThisMonth) <= 0
            && myCalenderFragment.getSelectTime().compareTo(firstDayThisMonth) >= 0) {
          queryDateStr = myCalenderFragment.getSelectTime();
        } else {
          queryDateStr = firstDayThisMonth;
        }

        loadDataByMonth(queryDateStr);
        loadHabitsPlan(queryDateStr);
        selectQueryDate = queryDateStr;
      }

    }
  }

  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onCheckClick() {

  }

  @Override
  public void onRemoteLogin() {
    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (device_stateview != null) {
          device_stateview.setPlaying(false);
        }
      }
    });

  }

  @Override
  public void onConnectionChanged(boolean connect) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPowerChanged(int power) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onUpgrade(int updatingStatus) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onCheckDeviceVersion(String version) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayNextFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayPrevFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayMedia(final PlayState playState, MediaType type,
                          final JSONObject data) {

    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        mPlayState = playState;

        String playType = "radio";
        if (data.has("type")) {
          playType = data.optString("type");
        }

        if (playState.equals(PlayState.Playing)) {
          device_stateview.setPlaying(true);
          if (data.has("VideoId")) {
            mVideoId = data.optInt("VideoId");
            if (!imgList.isEmpty()) {
              for (ImageView img : imgList) {
                int tag = (int) img.getTag();
                if (tag == mVideoId) {
                  img.setBackgroundResource(R.drawable.anim_pause);
                } else {
                  img.setBackgroundResource(R.drawable.anim_play);
                }
              }
            }
          }

          if (Tools.isNotEmpty(playType)
              && playType.equalsIgnoreCase("game")) {
            // 更新互动游戏
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(mVideoId, mPlayState);
            }
          } else {
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(-1, PlayState.None);
            }
          }

        } else if (playState.equals(PlayState.Pause)) {
          device_stateview.setPlaying(false);
          if (data.has("VideoId")) {
            mVideoId = data.optInt("VideoId");
          }



                if (!imgList.isEmpty()) {
                    for (ImageView img : imgList) {
                        img.setBackgroundResource(R.drawable.anim_play);
                    }
                }



          if (Tools.isNotEmpty(playType)
              && playType.equalsIgnoreCase("game")) {
            // 更新互动游戏
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(mVideoId, mPlayState);
            }
          } else {
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(-1, PlayState.None);
            }
          }
        } else {
          mVideoId = -1;
          device_stateview.setPlaying(false);
          if (!imgList.isEmpty()) {
            for (ImageView img : imgList) {
              img.setBackgroundResource(R.drawable.anim_play);
            }
          }

          if (Tools.isNotEmpty(playType)
              && playType.equalsIgnoreCase("game")) {
            // 更新互动游戏
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(mVideoId, mPlayState);
            }
          }
        }

      }
    });

  }

  @Override
  public void onReceivedVoiceMessage(String streamUrl) {
    // TODO Auto-generated method stub

  }

  @Override
  protected void onDestroy() {
    // unBind();

    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }

//    if (mImHelper != null) {
//      mImHelper.removeDataReceivedListener(this);
//      mImHelper.removeIMParseListener(this);
//    }

    unBind();

    releaseMp3Player();

    super.onDestroy();

  }

  private void unBind() {
    SocketThreadManager.getInstance().removeDeviceStateListener(this);
    SocketThreadManager.getInstance().removeDataReceivedListener(this);
  }

  @Override
  public void onScroll(AbsListView view, int firstVisibleItem,
      int visibleItemCount, int totalItemCount) {
    // TODO Auto-generated method stub

  }

  @Override
  public void finishSetAlarm2() {
    if (Tools.isNotEmpty(selectQueryDate)) {
      loadHabitsPlan(selectQueryDate);

    //  if (mImHelper != null && mImHelper.isLogin()) {
        JSONObject jsonObject = new JSONObject();
        try {
          jsonObject.put("code", 202);
          jsonObject.put("act", "habit_update");
          jsonObject.put("data", mLeUser.id);

          SocketThreadManager.getInstance().send(jsonObject.toString());
        } catch (JSONException e) {
          e.printStackTrace();
        }
    //  }
    }
  }

  @Override
  public void finishSetAlarm() {
    if (Tools.isNotEmpty(selectQueryDate)) {
      loadHabitsPlan(selectQueryDate);

    //  if (mImHelper != null && mImHelper.isLogin()) {
        JSONObject jsonObject = new JSONObject();
        try {
          jsonObject.put("code", 202);
          jsonObject.put("act", "habit_update");
          jsonObject.put("data", mLeUser.id);

          SocketThreadManager.getInstance().send(jsonObject.toString());
        } catch (JSONException e) {
          e.printStackTrace();
        }
     // }
    }
  }

  @Override
  public void onDataReceived(final String data) {

    runOnUiThread(new Runnable() {
      @Override
      public void run() {
      //  mHabitMusic = null;
        if (Tools.isNotEmpty(data)) {
          try {
            JSONObject jsonData = new JSONObject(data.toString());
            if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("act")
                    && jsonData.getString("act").contains("habit")) {
              String realData = jsonData.getString("data");
              if (Tools.isNotEmpty(realData)) {
                isPlayingMusic = true;
                mHabitMusic = JsonSerializer.getInstance().deserialize(realData,
                        HabitMedia.class);
                if (mHabitMusic != null) {
                  if (arrayListHabitPlan != null && arrayListHabitPlan.size() > 0) {
                    for (int i = 0; i < arrayListHabitPlan.size(); i++) {
                      HabitPlan item = arrayListHabitPlan.get(i);

                      if (item.is_customized == 1) {
                        if (item != null && item.id == mHabitMusic.id) {
                          listview_habitplan.setSelection(i);
                          break;
                        }
                      } else {
                        if (item != null && item.id == mHabitMusic.id) {
                          listview_habitplan.setSelection(i);
                          break;
                        }
                      }


                    }
                  }

                  if (Tools.isNotEmpty(mHabitMusic.PlayState)
                          && mHabitMusic.PlayState.contains("stop")) {
                    isPlayingMusic = false;
                  }

                  if (mHabitPlanAdapter != null) {
                    mHabitPlanAdapter.updatePlayingInfo(mHabitMusic);
                  }
                }
              }
            } else if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("code")
                    && jsonData.getString("code").contains("server")) {
              String loginStr = jsonData.getString("act");
              if (Tools.isNotEmpty(loginStr)) {
                if (loginStr.contains("Device_Login")) {
                  LeConfig.isDeviceConnect = true;
                } else if (loginStr.contains("Device_Logout")) {
                  LeConfig.isDeviceConnect = false;
                } else if (loginStr.contains("Device_APP_Connection_Switched")) {
                  // Jump to Login page

                  // Intent logoutIntent = new Intent(
                  // "com.jdy.haoduoai.activity.logout");
                  // sendBroadcast(logoutIntent);
                  //
                  // LeConfig.isLogin = false;
                  // LeConfig.isDeviceActivated = false;
                  // LeConfig.isDeviceBinded = false;
                  // LeConfig.isInfoFilled = false;
                  // LeConfig.isDeviceConnect = false;
                  //
                  // CustomOneBtnDialog.Builder cdb = new
                  // CustomOneBtnDialog.Builder(
                  // getApplicationContext())
                  // .setTitle("下线通知")
                  // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                  // .setPositiveButton("确定",
                  // new DialogInterface.OnClickListener() {
                  //
                  // @Override
                  // public void onClick(DialogInterface dialog, int which) {
                  // dialog.dismiss();
                  // }
                  // });
                  // final CustomOneBtnDialog cd = cdb.create();
                  // cd.getWindow().setType(
                  // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                  // cd.setOnDismissListener(new OnDismissListener() {
                  //
                  // @Override
                  // public void onDismiss(DialogInterface dialog) {
                  // Intent toActivityIntent = new Intent(
                  // BabyCalenderActivity.this, LoginActivity.class);
                  // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                  // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  // startActivity(toActivityIntent);
                  // finish();
                  // // dialog.dismiss();
                  // }
                  // });
                  // // cd.setCancelable(false);
                  // // cd.setCanceledOnTouchOutside(false);
                  // cd.show();
                }
              }
            } else if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("code")
                    && jsonData.getString("code").contains("device")) {
              String loginStr = jsonData.getString("act");

              if (loginStr.contains("Device_APP_Connection_Switched")) {
                // Jump to Login page

                // Intent logoutIntent = new Intent(
                // "com.jdy.haoduoai.activity.logout");
                // sendBroadcast(logoutIntent);
                //
                // LeConfig.isLogin = false;
                // LeConfig.isDeviceActivated = false;
                // LeConfig.isDeviceBinded = false;
                // LeConfig.isInfoFilled = false;
                // LeConfig.isDeviceConnect = false;
                //
                // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
                // getApplicationContext()).setTitle("下线通知")
                // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                //
                // @Override
                // public void onClick(DialogInterface dialog, int which) {
                // dialog.dismiss();
                // }
                // });
                // final CustomOneBtnDialog cd = cdb.create();
                // cd.getWindow()
                // .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                // cd.setOnDismissListener(new OnDismissListener() {
                //
                // @Override
                // public void onDismiss(DialogInterface dialog) {
                // Intent toActivityIntent = new Intent(BabyCalenderActivity.this,
                // LoginActivity.class);
                // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // startActivity(toActivityIntent);
                // finish();
                // // dialog.dismiss();
                // }
                // });
                // // cd.setCancelable(false);
                // // cd.setCanceledOnTouchOutside(false);
                // cd.show();
              }
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }
    });


  }

  @Override
  public void onDateSelected(String dateStr) {
    // showloading("");
    loadDataByMonth(dateStr);
    loadHabitsPlan(dateStr);
    selectQueryDate = dateStr;

    if (Tools.isNotEmpty(dateStr)) {
      tvCurrentMonth.setText(dateStr.subSequence(0, 4) + "年 "
          + dateStr.substring(5, 7) + "月");
    }

  }

//  @Override
//  public void onNetWorkDisconn() {
//    if (device_stateview != null) {
//      device_stateview.setPlaying(false);
//    }
//  }

  public void OnConfirmClick(int pos) {
    if (arrayListTeacherClass != null && pos < arrayListTeacherClass.size()) {
      arrayListTeacherClass.get(pos).checked = 1;
      mTeacherClassApater.setData(arrayListTeacherClass);
    }
  }

}
